package com.aholu.wicket.pages;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.aholu.dao.DaoFactory;
import com.aholu.model.User;
import com.aholu.validate.ValidateDate;
import com.aholu.validate.ValidateEmail;
import com.aholu.validate.ValidateName;
import com.aholu.validate.ValidatePass;

/**
 * 
 * Used to register new user
 * 
 * @author aholu
 * 
 */
public class RegisterPage extends WebPage {

	private Date date;
	private static final List<String> ROLES = Arrays.asList(new String[] { "admin", "standart" });
	private String selected = "standart";

	public Date getDate() {
		return date;
	}

	public RegisterPage() {

		add(new FeedbackPanel("feedBackPanel"));

		final TextField<String> username = new TextField<String>("username", Model.of(""));
		final TextField<String> password = new TextField<String>("password", Model.of(""));
		password.add(new ValidatePass());
		final TextField<String> firstname = new TextField<String>("firstname", Model.of(""));
		firstname.add(new ValidateName());
		final TextField<String> surname = new TextField<String>("surname", Model.of(""));
		surname.add(new ValidateName());
		final TextField<String> email = new TextField<String>("email", Model.of(""));
		email.add(new ValidateEmail());
		final DateTextField dateTextField = new DateTextField("dateTextField", new PropertyModel<Date>(this, "date")) {

		};
		dateTextField.add(new ValidateDate());
		final DropDownChoice<String> listRoles = new DropDownChoice<String>("roles", new PropertyModel<String>(this, "selected"), ROLES);

		Form<?> form = new Form<Void>("registerForm") {

			@Override
			protected void onSubmit() {

				User user = new User();

				String userValue = username.getValue();
				user.setUserName(userValue);
				String nameValue = firstname.getValue();
				user.setName(nameValue);
				String surnameValue = surname.getValue();
				user.setSurName(surnameValue);
				String emailValue = email.getValue();
				user.setEmail(emailValue);
				String passValue = password.getValue();
				user.setPassword(passValue);
				Date dateValue = dateTextField.getModelObject();
				user.setDate(dateValue);
				user.setRole(selected);

				DaoFactory.getUserDao().makePersistent(user);
				setResponsePage(AdminPage.class);

			}

		};

		form.add(username);
		form.add(password);
		form.add(firstname);
		form.add(surname);
		form.add(email);
		form.add(dateTextField);
		form.add(listRoles);
		add(form);
	}

}
